package com.zhangdi.demo.solr.controller.rest;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhangdi.demo.solr.entity.User;
import com.zhangdi.demo.solr.response.Response;
import com.zhangdi.demo.solr.response.ResponseUtils;
import com.zhangdi.demo.solr.service.UserService;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangdi on 2020/06/24 15:04:50.
 */

@RestController
public class TestController {
    Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    SolrClient solrClient;

    @Autowired
    UserService userService;

    @GetMapping("/solr/search")
    public List<User> query(String str){
        List<User> users = new ArrayList<>();

        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery("description:" + str);
        solrQuery.setStart(0);
        solrQuery.setRows(10);
        try {
            QueryResponse response = solrClient.query(solrQuery);
            SolrDocumentList documentList = response.getResults();
            if (!documentList.isEmpty()) {
                Gson gson = new Gson();
                String listString = gson.toJson(documentList);
                users = gson.fromJson(listString, new TypeToken<List<User>>() {}.getType());
                logger.info(">>>> query user from solr success <<<<");
            } else {
                users = userService.list();
                solrClient.addBeans(users);
                logger.info(">>>> query user from database <<<<");
            }
        } catch (SolrServerException | IOException e) {
            logger.error(e.getMessage(),e);
        }

        return users;
    }

    @PostMapping("/mg/user/add")
    public Response<User> addUser(@RequestBody User user){
        return userService.add(user);
    }

    @PostMapping("/mg/user/list")
    public Response<List<User>> list(){
        return ResponseUtils.success(userService.list());
    }

    @PostMapping("/mg/user/findbyids")
    public Response<List<User>> findByIds(){
        return ResponseUtils.success(userService.findById(null));
    }
}
